package com.whfc.iot.mach.codec;

import com.whfc.common.util.VersionUtil;
import com.whfc.iot.mach.entity.MachMsg0x82;
import io.netty.buffer.ByteBuf;

/**
 * @Description:
 * @author: xugcheng
 * @version: 1.0
 * @date: 2019/8/23 10:48
 */
public class MachMsgDataCodec0x82 implements MachMsgDataCodec<MachMsg0x82> {

    @Override
    public void decode(ByteBuf buf, MachMsg0x82 msg) {

        int masterOrSlave = buf.readUnsignedByte();
        int[] verArr = new int[3];
        verArr[0] = buf.readUnsignedByte();
        verArr[1] = buf.readUnsignedByte();
        verArr[2] = buf.readUnsignedByte();
        String ver = VersionUtil.getHardwareVersion(verArr);
        int subPackageTotal = buf.readUnsignedByte();
        int subPackageSeq = buf.readUnsignedByte();
        int subPackageLength = buf.readableBytes() - 1;
        byte[] subPackageData = new byte[subPackageLength];
        buf.readBytes(subPackageData);

        msg.setMasterOrSlave(masterOrSlave);
        msg.setVer(ver);
        msg.setVerArr(verArr);
        msg.setSubPackageTotal(subPackageTotal);
        msg.setSubPackageSeq(subPackageSeq);
        msg.setSubPackageData(subPackageData);
    }

    @Override
    public void encode(ByteBuf buf, MachMsg0x82 msg) {

        buf.writeByte(msg.getMasterOrSlave());
        int[] verArr = VersionUtil.parseHardvareVersion(msg.getVer());
        for (int ver : verArr) {
            buf.writeByte(ver);
        }
        buf.writeByte(msg.getSubPackageTotal());
        buf.writeByte(msg.getSubPackageSeq());
        if (msg.getSubPackageData() != null) {
            buf.writeBytes(msg.getSubPackageData());
        }

    }
}
